#!/bin/bash

echo "🔍 PostgreSQL连接问题诊断"
echo "=========================="

echo ""
echo "1️⃣ 检查Docker容器状态..."
echo "当前运行的PostgreSQL容器:"
sudo docker ps | grep postgres

echo ""
echo "2️⃣ 检查环境变量..."
echo "DATABASE_URL: $DATABASE_URL"

echo ""
echo "3️⃣ 检查PostgreSQL容器日志..."
echo "最近的容器日志:"
POSTGRES_CONTAINER=$(sudo docker ps | grep postgres | awk '{print $1}' | head -1)
if [ ! -z "$POSTGRES_CONTAINER" ]; then
    echo "容器ID: $POSTGRES_CONTAINER"
    sudo docker logs --tail 20 $POSTGRES_CONTAINER
else
    echo "❌ 没有找到运行中的PostgreSQL容器"
fi

echo ""
echo "4️⃣ 尝试连接测试..."
if [ ! -z "$DATABASE_URL" ]; then
    echo "尝试使用DATABASE_URL连接..."
    # 解析DATABASE_URL
    DB_USER=$(echo $DATABASE_URL | sed 's/.*:\/\/\([^:]*\):.*/\1/')
    DB_PASS=$(echo $DATABASE_URL | sed 's/.*:\/\/[^:]*:\([^@]*\)@.*/\1/')
    DB_HOST=$(echo $DATABASE_URL | sed 's/.*@\([^:]*\):.*/\1/')
    DB_PORT=$(echo $DATABASE_URL | sed 's/.*:\([0-9]*\)\/.*/\1/')
    DB_NAME=$(echo $DATABASE_URL | sed 's/.*\/\([^?]*\).*/\1/')
    
    echo "解析结果:"
    echo "  用户: $DB_USER"
    echo "  密码: ${DB_PASS:0:3}***"
    echo "  主机: $DB_HOST"
    echo "  端口: $DB_PORT"
    echo "  数据库: $DB_NAME"
    
    echo ""
    echo "测试连接..."
    if command -v psql &> /dev/null; then
        PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "SELECT version();" 2>&1 | head -5
    else
        echo "psql未安装，跳过直接连接测试"
    fi
else
    echo "❌ DATABASE_URL环境变量未设置"
fi

echo ""
echo "5️⃣ 推荐解决方案..."
echo "基于诊断结果，请尝试以下解决方案:"
echo ""
echo "方案A: 重新设置正确的DATABASE_URL"
echo "  export DATABASE_URL=\"postgresql://postgres:aide123456@localhost:5432/aide\""
echo ""
echo "方案B: 重新创建PostgreSQL容器"
echo "  sudo docker stop postgres-aide"
echo "  sudo docker rm postgres-aide"
echo "  sudo docker volume rm postgres_data"
echo "  sudo docker run --name postgres-aide -e POSTGRES_PASSWORD=aide123456 -e POSTGRES_DB=aide -p 5432:5432 -v postgres_data:/var/lib/postgresql/data -d postgres:latest"
echo ""
echo "方案C: 检查容器内的密码设置"
echo "  sudo docker exec -it postgres-aide psql -U postgres"
